<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use App\V3\V3_2_7\Services\ShelfService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

/**
 * 库位管理
 * AUTHOR  : zl
 * DateTime: 2022/08/22
 */
class LocationController extends BaseController
{

    /**
     * 添加库位
     */
    public function LocationCreate(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'locationName' => 'required|string',//库位名称
            'shelfId' => 'required|integer',//货架ID
            'storageId' => 'required|integer',//仓库ID
            'standard_num' => 'nullable|numeric',
        ], [
            'locationName.required' => '参数`locationName`缺失',
            'locationName.string' => '参数`locationName`仅能为字符串',
            'shelfId.required' => '参数`shelfId`缺失',
            'shelfId.integer' => '参数`shelfId`仅能为数字',
            'storageId.required' => '参数`storageId`缺失',
            'storageId.integer' => '参数`storageId`仅能为数字',
            'standard_num.numeric' => '参数`标准数量`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

//        if(empty(ShelfService::is_use_shelf($this->getMainUserId()))){
//            return $this->fail('','未开启货架功能');
//        }
        if (StorageShelfLocationModel::query()->where([
            'status' => 1,
            'main_id' => $this->getMainUserId(),
            'location_name' => $data['locationName'],
            'storage_id' => $request->storageId
        ])->exists()) {
            return $this->fail('', '同仓库下，库位名称不能重复！');
        }
        $location = new StorageShelfLocationModel();
        $location->location_name = $request->locationName;
        $location->main_id = $this->getMainUserId();
        $location->storage_id = $request->storageId;
        $location->shelf_id = $request->shelfId;
        $location->location_type = StorageShelfLocationModel::CREATETYPE;
        $location->remark = empty($data['remark']) ? '' : $data['remark'];
        $location->sort = empty($data['sort']) ? 0 : $data['sort'];
        if (isset($data['standard_num']))
            $location->standard_num = $data['standard_num'];
        $location->log_no = getNO('storage_shelf_location', 'log_no');
        $res = $location->save();

        if ($res) {
            $this->log('添加库位', $data, '库位名称:' . $location->location_name . ',创建成功!');
            return $this->success('', '添加成功');
        } else {
            return $this->fail('', '添加失败');
        }
    }

    /**
     * 添加库位
     */
    public function LocationUpdate(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'locationName' => 'required|string',//库位名称
//            'shelfId' =>'required|integer',//货架ID
            'locationId' => 'required|integer',//库位ID
        ], [
            'locationName.required' => '参数`locationName`缺失',
            'locationName.string' => '参数`locationName`仅能为字符串',
//            'shelfId.required' => '参数`shelfId`缺失',
//            'shelfId.integer' => '参数`shelfId`仅能为数字',
            'locationId.required' => '参数`locationId`缺失',
            'locationId.integer' => '参数`locationId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

//        if(empty(ShelfService::is_use_shelf($this->getMainUserId()))){
//            return $this->fail('','未开启货架功能');
//        }

        $info = StorageShelfLocationModel::where('id', $data['locationId'])
            ->where('main_id', $this->getMainUserId())
            ->where('status', StorageShelfModel::USEDSTATUS)->first();
        if(empty($info)){
            return $this->fail('', '无库位信息！');
        }
        if (StorageShelfLocationModel::query()->where([
            'status' => 1,
            'main_id' => $this->getMainUserId(),
            'location_name' => $data['locationName'],
            ['id','!=',$info['id']],
            'storage_id' => $info['storage_id']
        ])->exists()) {
            return $this->fail('', '同仓库下，库位名称不能重复！');
        }
        $updData = [
            'location_name' => $data['locationName'],
            'remark' => empty($data['remark']) ? "" : $data['remark'],
            'sort' => empty($data['sort']) ? 1 : $data['sort'],
        ];
        if (isset($data['standard_num']))
            $updData['standard_num'] = $data['standard_num'];
        $res = StorageShelfLocationModel::where('id', $data['locationId'])
            ->where('main_id', $this->getMainUserId())
            ->where('status', StorageShelfModel::USEDSTATUS)
            ->update($updData);

        if ($res) {
            $this->log('添加库位', $data, '库位名称:' . $data['locationName'] . ',信息已修改!');
            return $this->success('', '修改成功');
        } else {
            return $this->fail('', '修改失败');
        }

    }

    public function LocationDel(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'locationId' => 'required|integer',//货架ID
        ], [
            'locationId.required' => '参数`locationId`缺失',
            'locationId.integer' => '参数`locationId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

//        if(empty(ShelfService::is_use_shelf($this->getMainUserId()))){
//            return $this->fail('','未开启货架功能');
//        }

        $location_info = StorageShelfLocationModel::where('id', $data['locationId'])->first();

        if ($location_info['location_type'] == StorageShelfLocationModel::DEFAULTTYPE) {
            return $this->fail('', '默认库位不能删除');
        }

        $judging_status = ShelfService::judging_del($data['locationId'], 3, $this->getMainUserId());

        if (!empty($judging_status)) {
            $res = StorageShelfLocationModel::where('id', $data['locationId'])
                ->where('main_id', $this->getMainUserId())
                ->where('status', StorageShelfLocationModel::USEDSTATUS)
                ->update(['status' => StorageShelfLocationModel::DELETESTATUS]);

            if ($res) {
                $this->log('删除库位', $data, '库位名称:' . $location_info['location_name'] . ',信息已删除!');

                return $this->success('', '删除成功');
            } else {
                return $this->fail('', '删除失败');
            }
        } else {
            return $this->fail('', '此库位还有库存商品，不能删除');
        }

    }

    public function LocationList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'shelfId' => 'required|integer',//货架ID
        ], [
            'shelfId.required' => '参数`storageId`缺失',
            'shelfId.integer' => '参数`storageId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        return $this->success(
            ShelfService::location_list($this->getMainUserId(), $data)
        );
    }

    /**
     * 库位详情
     */
    public function LocationInfo(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'locationId' => 'required|integer',//货架ID
        ], [
            'locationId.required' => '参数`locationId`缺失',
            'locationId.string' => '参数`locationId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $info = StorageShelfLocationModel::query()
            ->where('id', $data['locationId'])
            ->where('main_id', $this->getMainUserId())
            ->where('status', StorageShelfModel::USEDSTATUS)->first();

        if (empty($info)) {
            return $this->fail('', '没查询到相关数据');
        }

        $storage = StorageModel::where(['id' => $info['storage_id']])->first();
        $shelf = StorageShelfModel::where(['id' => $info['shelf_id']])->first();

        $res = [];
        $res['storage_name'] = $storage['storage_name'];
        $res['storage_id'] = $storage['id'];
        $res['shelf_id'] = $shelf['id'];
        $res['shelf_name'] = $shelf['shelf_name'];
        $res['location_id'] = $info['id'];
        $res['location_name'] = $info['location_name'];
        $res['remark'] = $info['remark'];
        $res['sort'] = $info['sort'];
        $res['standard_num'] = $info['standard_num'];
        $res['total_num'] = StorageManageModel::query()
            ->where([
                'location_id' => $info['id'],
                'storage_id' => $storage['id'],
                'shelf_id' => $shelf['id'],
                'delete_flag' => 0,
                'main_id' => $this->getMainUserId()
            ])->sum('in_storage_num');
        return $this->success($res, '获取成功');
    }

    /**
     *批量添加货架与库位
     * Author: zlf
     * Created at 2024/6/26 9:53
     * @param Request $request
     * @return JsonResponse
     */
    public function shelfLocationAdd(Request $request): JsonResponse
    {
        $validator = Validator::make($data = $request->all(), [
            'shelf_location_data' => 'required|json',//货架库位数据
            'shelf_id' => 'nullable|integer',
            'storage_id' => 'required|integer',
            'standard_num' => 'nullable|numeric',
        ], [
            'shelf_location_data.required' => '参数`货架库位数据`缺失',
            'shlef_location_data.json' => '参数`货架库位数据`类型为JSON',
            'shelf_id.integer' => '参数`库位主键`为整数！',
            'storage_id.required' => '参数`仓库主键`缺失！',
            'storage_id.integer' => '参数`仓库主键`为整数！',
            'standard_num.numeric' => '参数`标准数量`为数字！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail($info);
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();

        $this->operateLog('批量添加货架与库位', $data, $data['time']);
        return Cache::lock($data['storage_id'] . __CLASS__ . __FUNCTION__ . $data['user_id'], 10)
            ->get(function () use ($data) {
                // 锁定 10 秒并自动释放...
                return response()->json(ShelfService::shelfLocationAdd($data));
            });
    }
}
